package custcare

import (
	"fmt"
	"strings"
	"wave-admin/global"
	"wave-admin/model/custcare"
	"wave-admin/model/custcare/request"
	"wave-admin/model/custcare/response"
)

type ReplyService struct{}

func (replyService *ReplyService) ReplyKeyWordCount(keyWord string) (count int64) {
	err := global.GnDb.Model(&custcare.CusReplyKeyWord{}).Where("key_word=?", keyWord).Count(&count).Error
	if err != nil {
		return 0
	}
	return count
}

func (replyService *ReplyService) AddReplyKeyWord(replyId uint64, keyWords string) (err error) {
	words := strings.Split(keyWords, ",")
	for _, word := range words {
		// 关键字是唯一的
		count := replyService.ReplyKeyWordCount(word)
		if count <= 0 {
			keywords := custcare.CusReplyKeyWord{
				ReplyId: replyId,
				KeyWord: word,
			}
			err = global.GnDb.Create(&keywords).Error
			if err != nil {
				return err
			}
		}
	}
	return nil
}

func (replyService *ReplyService) AddReply(reply request.ReqReply) (err error) {
	add := custcare.CusReply{
		Status:   reply.Status,
		GroupId:  reply.GroupId,
		Question: reply.Question,
		Content:  reply.Content,
		Img:      reply.Img,
		Sort:     reply.Sort,
	}
	err = global.GnDb.Create(&add).Error
	if err != nil {
		return err
	}
	err = replyService.AddReplyKeyWord(add.ID, reply.KeyWords)

	if add.GroupId == 1 || add.GroupId == 3 {
		err = replyService.AddRedisReplySet(add.ID)
	}

	return err
}

func (replyService *ReplyService) UpdateReply(reply request.ReqReply, id int) (err error) {
	update := custcare.CusReply{
		Status:   reply.Status,
		GroupId:  reply.GroupId,
		Question: reply.Question,
		Content:  reply.Content,
		Img:      reply.Img,
		Sort:     reply.Sort,
	}
	err = global.GnDb.Model(&custcare.CusReply{}).Where("id=?", id).Updates(update).Error
	if err != nil {
		return err
	}

	replyService.DelRedisReply(id, update.Question)

	err = global.GnDb.Delete(&custcare.CusReplyKeyWord{}, "reply_id = ?", id).Error
	if err != nil {
		return err
	}

	//if update.GroupId == 1 || update.GroupId == 3 {
	//	err = replyService.AddRedisReplySet(uint64(id))
	//}

	err = replyService.AddReplyKeyWord(uint64(id), reply.KeyWords)

	return err
}

func (replyService *ReplyService) DelRedisReply(id int, question string) (err error) {
	cacheCusRepliesIdPrefix := fmt.Sprintf("cache:cusReplies:id:%d", id)
	cacheCusRepliesQuestionPrefix := fmt.Sprintf("cache:cusReplies:question:%s", question)
	global.GnRedis.Del(cacheCusRepliesIdPrefix)
	return global.GnRedis.Del(cacheCusRepliesQuestionPrefix).Err()
}

func (replyService *ReplyService) AddRedisReplySet(id uint64) (err error) {
	cacheCusRepliesSetPrefix := "cache:cusReplies:set"
	return global.GnRedis.SAdd(cacheCusRepliesSetPrefix, id).Err()
}

func (replyService *ReplyService) DeleteReply(id int) (err error) {
	err = global.GnDb.Where("reply_id = ?", id).Unscoped().Delete(&custcare.CusReplyKeyWord{}).Error
	if err != nil {
		return err
	}
	err = global.GnDb.Delete(&custcare.CusReply{}, "id = ?", id).Error

	err = replyService.DelRedisReplySet(uint64(id))

	return err
}

func (replyService *ReplyService) DelRedisReplySet(id uint64) (err error) {
	cacheCusRepliesSetPrefix := "cache:cusReplies:set"
	return global.GnRedis.SRem(cacheCusRepliesSetPrefix, id).Err()
}

func (replyService *ReplyService) GetSort() (reply custcare.CusReply, err error) {
	err = global.GnDb.Order("sort DESC").Find(&reply).Error

	return reply, err
}

func (replyService *ReplyService) GetReplyList(info request.ReplyList) (list interface{}, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.CurrentPage - 1)
	var replys []custcare.CusReply
	db := global.GnDb.Model(&custcare.CusReply{}).Where("status = ?", info.Status).Order("sort")
	if info.Content != "" {
		db = db.Where("content LIKE ?", "%"+info.Content+"%")
	}
	if info.GroupId != 0 {
		db = db.Where("group_id = ?", info.GroupId)
	}

	err = db.Count(&total).Error
	if err != nil {
		return replys, total, err
	}

	err = db.Limit(limit).Offset(offset).Find(&replys).Error

	for i, reply := range replys {
		var keywords []custcare.CusReplyKeyWord
		global.GnDb.Model(&custcare.CusReplyKeyWord{}).Where("reply_id = ?", reply.ID).Find(&keywords)
		for j, kw := range keywords {
			if j > 0 {
				replys[i].KeyWords = replys[i].KeyWords + "," + kw.KeyWord
			} else {
				replys[i].KeyWords = kw.KeyWord
			}
		}
		var group custcare.CusReplyGroup
		global.GnDb.Model(&custcare.CusReplyGroup{}).Where("id = ?", reply.GroupId).First(&group)
		replys[i].GroupName = group.Name
	}

	return replys, total, err
}

func (replyService *ReplyService) SelectReplyGroupList() (list []response.SelectReplyGroup, err error) {
	var replyGroups []custcare.CusReplyGroup
	err = global.GnDb.Model(&custcare.CusReplyGroup{}).Find(&replyGroups).Error
	for _, g := range replyGroups {
		list = append(list, response.SelectReplyGroup{
			ID:   g.ID,
			Name: g.Name,
		})
	}

	return list, err
}
